// 引入依赖包
const gulp = require('gulp')
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const css = require('gulp-clean-css')
const sass = require('gulp-sass')
const htmlmin = require('gulp-htmlmin')
const connect = require('gulp-connect')
const del = require('del')

// 定义路径信息
const paths = {
  // 待处理的js文件相关路径
  js: {
    src: 'src/js/**/*.js', // 源
    dest: 'dist/js', // 目标
  },
  // css文件路径
  css: {
    src: 'src/css/**/*.css',
    dest: 'dist/css'
  },
  // scss 文件路径
  scss: {
    src: 'src/scss/**/*.scss',
    dest: 'dist/css'
  },
  // html 文件路径
  html: {
    src: 'src/**/*.html',
    dest: 'dist'
  },
  // libs 资源
  lib: {
    src: 'src/libs/**/*.*',
    dest: 'dist/libs'
  },
  // 图像资源
  image: {
    src: 'src/images/**/*.*',
    dest: 'dist/images'
  },
  // mock数据
  mock: {
    src: 'src/mock/**/*.json',
    dest: 'dist/mock'
  },
}

// 定义任务函数，实现 js 文件处理
const scripts = () => {
  return gulp.src(paths.js.src)
    .pipe(babel({ // 转译
			presets: ['env']
		}))
    .pipe(uglify()) // 压缩
    .pipe(gulp.dest(paths.js.dest)) // 放到目标目录中
    .pipe(connect.reload()) // 刷新浏览器
}

// 定义处理 css 文件资源的任务
const styles = () => gulp.src(paths.css.src)
  .pipe(css())
  .pipe(gulp.dest(paths.css.dest))
  .pipe(connect.reload())

// 编译 scss 文件
const scsses = () => gulp.src(paths.scss.src)
  .pipe(sass({outputStyle: 'compressed'}))
  .pipe(gulp.dest(paths.scss.dest))
  .pipe(connect.reload())

// html 文件压缩
const htmls = () => gulp.src(paths.html.src)
  .pipe(htmlmin({ collapseWhitespace: true, minifyJS: true, minifyCSS: true }))
  .pipe(gulp.dest(paths.html.dest))
  .pipe(connect.reload())

// 复制 libs、images 目录下的资源
const copyLibs = () => gulp.src(paths.lib.src)
  .pipe(gulp.dest(paths.lib.dest))
const copyImages = () => gulp.src(paths.image.src)
  .pipe(gulp.dest(paths.image.dest))
const copyMock = () => gulp.src(paths.mock.src)
  .pipe(gulp.dest(paths.mock.dest))
const copy = gulp.parallel(copyLibs, copyImages, copyMock)

// 清理 dist 目录
const clean = () => del(['dist'])

// 监视任务
const watch = () => {
  gulp.watch(paths.js.src, scripts)
  gulp.watch(paths.css.src, styles)
  gulp.watch(paths.scss.src, scsses)
  gulp.watch(paths.html.src, htmls)
}

// 启动 webserver
const server = () => {
  connect.server({
    root: 'dist', // 启动服务器时，指定 webserver 的根目录
    port: 3000, // 端口
    livereload: true, // 启动浏览器自动刷新功能
  })
}

// 定义构建任务，组织流程
const build = gulp.series(clean, gulp.parallel(scripts, styles, scsses, htmls, copy, watch, server))

// 导出任务，在命令行中执行 `gulp 任务名称` 可执行指定任务
exports.scripts = scripts
exports.styles = styles
exports.scsses = scsses
exports.htmls = htmls
exports.watch = watch
exports.server = server

// 导出默认任务，即在命令行中直接使用 `gulp` 可执行到的任务
exports.default = build
